<script setup>
import {ref, computed, onMounted, watch} from 'vue'
import {useCartStore} from '@/stores/cart.ts'
import {useUserStore} from '@/stores/user.ts'
import {changeCountAPI} from '@/apis/cart.ts'
import {storeToRefs} from 'pinia'
import {useRouter} from 'vue-router'
const router = useRouter()
const cartStore = useCartStore()
//const {cartList} = storeToRefs(cartStore) 
const cartList = ref([])
console.log(cartList)
const userStore = useUserStore()
//是否全选
const isCheckeAll = ref(false)
//不确定状态
const isIndeterminate = ref(false)

//总商品数量
const sumCount = computed(() => {
  let sumData = 0
  cartList.value.forEach(item => sumData += item.count)
  return sumData
})
//总商品金额
const sumPrice = computed(() => {
  let sum = 0;
  cartList.value.forEach(item => {
    if (item.selected) {
      sum += item.price * item.count
    }
  });
  return sum
})
//选择商品数量
const selectedCount = computed(() => {
  let sum = 0
  cartList.value.forEach((item) => {
    if (item.selected) {
      sum += item.count
    }
  })
  return sum
})
//点击商品选中按钮
const checke = (isChecke, skuId) => {
  let index = cartList.value.findIndex(item => item.skuId === skuId)
  cartList.value[index].selected = isChecke
  cartStore.updataChecke(isChecke, skuId)
  isSelectFanc()
}
//点击全选按钮
const checkAll = () => {
  isIndeterminate.value = false
  cartList.value.forEach(item => item.selected = isCheckeAll.value)
  cartStore.updataChecke(isCheckeAll.value)
}

//全选||不确定状态
const isSelectFanc = () => {
  //判断是否全选
  let checkeCount = 0
  checkeCount = cartList.value.filter(item => item.selected).length
  isCheckeAll.value = cartList.value.every(item => item.selected)
  //判断不确定状态
  isIndeterminate.value = !isCheckeAll.value && checkeCount > 0
}
//获取购物车列表
const getCart = async () => {
  // await cartStore.initCart()
  cartList.value = cartStore.cartList
  // await cartStore.initCart()
  // clone(cartList.value,cartStore.cartList)
  // for (let i=0;i< cartStore.cartList.length;i++){
  //   cartList.value[i] =  cartStore.cartList[i]
  // }
  // console.log('购物车列表：',cartList.value)
}

function clone(target, cloneObj) {
  for (let i = 0; i < cloneObj.length; i++) {
    target[i] = cloneObj[i]
  }
}

//删除商品
const delCart = async (skuId) => {
  let arr = []
  if (skuId instanceof Array) {
    arr = skuId
  } else {
    arr.push(skuId)
  }
  await cartStore.delCart(arr)
  // await cartStore.initCart()
  // cartList.value = cartStore.cartList
  //更新列表

}
//修改商品数量
const changeCount = async (data) => {
  if (userStore.user.token) {
    const {skuId, selected, count} = data
    const res = await changeCountAPI(skuId, selected, count)
    console.log(res)
  }
}
onMounted(async () => {
      isSelectFanc()
      await getCart()
    }
)
</script>

<template>
  <div class="xtx-cart-page">
    <div class="container m-top-20">
      <div class="cart">
        <table>
          <thead>
          <tr v-if="cartList.length != 0">
            <th width="120">
              <el-checkbox v-model="isCheckeAll" :indeterminate="isIndeterminate" @change="checkAll()"/>
            </th>
            <th width="400">商品信息</th>
            <th width="220">单价</th>
            <th width="180">数量</th>
            <th width="180">小计</th>
            <th width="140">操作</th>
          </tr>
          <tr v-else>
            <th colspan="6" width="1300px"></th>
          </tr>
          </thead>
          <!-- 商品列表 -->
          <tbody>
          <tr v-for="i in cartList" :key="i.id">
            <td>
              <el-checkbox @change="checke(i.selected,i.skuId)" v-model="i.selected"/>
            </td>
            <td>
              <div class="goods">
                <RouterLink to="/"><img :src="i.picture" alt=""/></RouterLink>
                <div>
                  <p class="name ellipsis">
                    {{ i.name }}
                  </p>
                </div>
              </div>
            </td>
            <td class="tc">
              <p>&yen;{{ i.price }}</p>
            </td>
            <td class="tc">
              <el-input-number v-model="i.count" min="1" max="99" @change="changeCount(i)"/>
            </td>
            <td class="tc">
              <p class="f16 red">&yen;{{ (i.price * i.count).toFixed(2) }}</p>
            </td>
            <td class="tc">
              <p>
                <el-popconfirm title="确认删除吗?" confirm-button-text="确认" cancel-button-text="取消"
                               @confirm="delCart(i.skuId)">
                  <template #reference>
                    <a href="javascript:;">删除</a>
                  </template>
                </el-popconfirm>
              </p>
            </td>
          </tr>
          <tr v-if="cartList.length === 0">
            <td colspan="6">
              <div class="cart-none">
                <el-empty description="购物车列表为空">
                  <el-button type="primary">随便逛逛</el-button>
                </el-empty>
              </div>
            </td>
          </tr>
          </tbody>

        </table>
      </div>
      <!-- 操作栏 -->
      <div class="action" v-if="cartList.length != 0">
        <div class="batch">
          共 {{ sumCount }} 件商品，已选择 {{ selectedCount }} 件，商品合计：
          <span class="red">¥ {{ sumPrice }} </span>
        </div>
        <div class="total" v-if="selectedCount>0">
          <el-button size="large" type="primary" @click="router.push('/checkout')">下单结算</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.xtx-cart-page {
  margin-top: 20px;

  .cart {
    background: #fff;
    color: #666;

    table {
      border-spacing: 0;
      border-collapse: collapse;
      line-height: 24px;

      th,
      td {
        padding: 10px;
        border-bottom: 1px solid #f5f5f5;

        &:first-child {
          text-align: left;
          padding-left: 30px;
          color: #999;
        }
      }

      th {
        font-size: 16px;
        font-weight: normal;
        line-height: 50px;
      }
    }
  }

  .cart-none {
    text-align: center;
    padding: 120px 0;
    background: #fff;

    p {
      color: #999;
      padding: 20px 0;
    }
  }

  .tc {
    text-align: center;

    a {
      color: $xtxColor;
    }

    .xtx-numbox {
      margin: 0 auto;
      width: 120px;
    }
  }

  .red {
    color: $priceColor;
  }

  .green {
    color: $xtxColor;
  }

  .f16 {
    font-size: 16px;
  }

  .goods {
    display: flex;
    align-items: center;

    img {
      width: 100px;
      height: 100px;
    }

    > div {
      width: 280px;
      font-size: 16px;
      padding-left: 10px;

      .attr {
        font-size: 14px;
        color: #999;
      }
    }
  }

  .action {
    display: flex;
    background: #fff;
    margin-top: 20px;
    height: 80px;
    align-items: center;
    font-size: 16px;
    justify-content: space-between;
    padding: 0 30px;

    .xtx-checkbox {
      color: #999;
    }

    .batch {
      a {
        margin-left: 20px;
      }
    }

    .red {
      font-size: 18px;
      margin-right: 20px;
      font-weight: bold;
    }
  }

  .tit {
    color: #666;
    font-size: 16px;
    font-weight: normal;
    line-height: 50px;
  }

}
</style>